/*
 * Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 * This file is part of e3ds.
 *
 * e3ds is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * e3ds is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with e3ds. If not, see <https://www.gnu.org/licenses/>.
 */

package rbmap

import "cmp"

const (
	red = iota
	black
)

func newNode[K cmp.Ordered, V any](m *RBMap[K, V], key K, val V) *node[K, V] {
	n := m.pool.Get().(*node[K, V])
	n.father = nil
	n.left = m.leaf
	n.right = m.leaf
	n.color = red

	n.iter.m = m
	n.iter.n = n
	n.iter.prev = nil
	n.iter.next = nil
	n.iter.key = key
	n.iter.ctx = val
	return n
}

func freeNode[K cmp.Ordered, V any](n *node[K, V]) {
	m := n.iter.m
	n.father = nil
	n.left = m.leaf
	n.right = m.leaf
	n.color = red

	n.iter.m = nil
	n.iter.n = nil
	n.iter.prev = nil
	n.iter.next = nil
	n.iter.key = m.zeroK
	n.iter.ctx = m.zeroV
	m.pool.Put(n)
}

type node[K cmp.Ordered, V any] struct {
	father *node[K, V]
	left   *node[K, V]
	right  *node[K, V]
	color  int
	iter   *Iterator[K, V]
}

func (ts *node[K, V]) isRoot() bool {
	return ts.father == nil
}

func (ts *node[K, V]) grandfather() *node[K, V] {
	if ts.isRoot() {
		return nil
	}
	return ts.father.father
}

func (ts *node[K, V]) uncle() *node[K, V] {
	if ts.grandfather() == nil {
		return nil
	}
	return ts.father.brother()
}

func (ts *node[K, V]) brother() *node[K, V] {
	if ts.father.left == ts {
		return ts.father.right
	} else {
		return ts.father.left
	}
}
